package cn.qrx.gateway.session;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.Callable;

/**
 * @author 屈燃希
 * @date 2025/10/1 14:40
 * @content 会话服务器实现类，实现Callable接口，可以异步启动Netty服务器
 */
public class SessionServer implements Callable<Channel> {

    private final Logger logger = LoggerFactory.getLogger(SessionServer.class) ; // 日志记录器

    private Channel channel; // 通道对象

    private EventLoopGroup boss = new NioEventLoopGroup(1); // BOSS线程组，负责接收连接

    private EventLoopGroup work = new NioEventLoopGroup(); // WORK线程组，负责处理IO


    private final Configuration configuration;

    public SessionServer(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public Channel call() throws Exception {
        ChannelFuture channelFuture =null;
        try {
            // 创建服务器引导对象
            ServerBootstrap b = new ServerBootstrap();
            // 配置服务器参数
            b.group(boss, work)  // 设置线程组
                    .channel(NioServerSocketChannel.class)  // 使用NIO模式
                    .option(ChannelOption.SO_BACKLOG, 128)  // 设置TCP连接队列大小
                    .childHandler(new SessionChannelInitializer(configuration));  // 设置通道初始化器

            // 绑定端口并启动服务器
            channelFuture = b.bind(new InetSocketAddress(7397)).syncUninterruptibly();
            this.channel = channelFuture.channel();
        } catch (Exception e) {
            logger.error("socket server start error.", e);
        } finally {
            // 判断服务器是否启动成功
            if (null != channelFuture && channelFuture.isSuccess()) {
                logger.info("socket server start done.");
            } else {
                logger.error("socket server start error.");
            }
        }
        return channel;
    }

}
